<template>
  <view class="date-picker-overlay" v-if="visible" @click.stop="closeOnMaskClick ? close() : null">
    <view class="date-picker-container" @click.stop>
      <view class="date-picker-header">
        <text class="cancel-btn" @click="close">取消</text>
        <text class="title">选择日期</text>
        <text class="confirm-btn" @click="confirm">确定</text>
      </view>
      
      <view class="date-picker-content">
        <!-- 年份选择器 -->
        <picker-view class="picker-view" :indicator-style="indicatorStyle" :value="selectedIndexes" @change="onChange">
          <picker-view-column>
            <view class="picker-item" v-for="(year, index) in years" :key="'year-' + index">{{ year }}</view>
          </picker-view-column>
          
          <picker-view-column>
            <view class="picker-item" v-for="(month, index) in months" :key="'month-' + index">{{ month }}</view>
          </picker-view-column>
        </picker-view>
      </view>
      
      <view class="date-picker-footer">
        <view class="indicator"></view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

// 定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  initialDate: {
    type: String,
    default: ''
  },
  startYear: {
    type: Number,
    default: 2020
  },
  endYear: {
    type: Number,
    default: 2030
  },
  closeOnMaskClick: {
    type: Boolean,
    default: true
  }
});

// 定义事件
const emit = defineEmits(['update:visible', 'confirm', 'cancel']);

// 获取当前日期
const now = ref(new Date());
const currentYear = ref(now.value.getFullYear());
const currentMonth = ref(now.value.getMonth() + 1); // 月份从0开始，需要+1

// 生成年份和月份数据
const years = computed(() => {
  const result = [];
  // 限制最大年份为当前年份
  const maxYear = Math.min(props.endYear, currentYear.value);
  for (let i = props.startYear; i <= maxYear; i++) {
    result.push(i);
  }
  return result;
});

const months = computed(() => {
  const result = [];
  // 如果是当前年份，则只显示到当前月份
  const maxMonth = selectedIndexes.value[0] === years.value.findIndex(y => y === currentYear.value) 
    ? currentMonth.value 
    : 12;
  
  for (let i = 1; i <= maxMonth; i++) {
    // 格式化月份，保证是两位数
    result.push(i < 10 ? `0${i}` : `${i}`);
  }
  return result;
});

// 当前选中的索引
const selectedIndexes = ref([0, 0]);

// 指示器样式
const indicatorStyle = 'height: 40px; line-height: 40px;';

// 初始化选中的日期
const initSelectedDate = () => {
  if (props.initialDate) {
    const [year, month] = props.initialDate.split('.');
    const parsedYear = parseInt(year);
    const parsedMonth = month;
    
    // 确保初始日期不超过当前日期
    const validYear = parsedYear > currentYear.value ? currentYear.value : parsedYear;
    const validMonth = validYear === currentYear.value && parseInt(parsedMonth) > currentMonth.value 
      ? (currentMonth.value < 10 ? `0${currentMonth.value}` : `${currentMonth.value}`) 
      : parsedMonth;
    
    const yearIndex = years.value.findIndex(y => y === validYear);
    const monthIndex = months.value.findIndex(m => m === validMonth);
    
    selectedIndexes.value = [
      yearIndex > -1 ? yearIndex : 0,
      monthIndex > -1 ? monthIndex : 0
    ];
  } else {
    // 默认选中当前年月
    const yearIndex = years.value.findIndex(y => y === currentYear.value);
    const monthIndex = months.value.findIndex(m => parseInt(m) === currentMonth.value);
    
    selectedIndexes.value = [
      yearIndex > -1 ? yearIndex : 0,
      monthIndex > -1 ? monthIndex : 0
    ];
  }
};

// 监听visible变化，当显示时初始化日期
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 更新当前日期，确保使用最新的日期限制
    now.value = new Date();
    currentYear.value = now.value.getFullYear();
    currentMonth.value = now.value.getMonth() + 1;
    initSelectedDate();
  }
});

// 初始化
initSelectedDate();

// 处理选择器变化
const onChange = (e) => {
  const newIndexes = [...e.detail.value];
  const selectedYear = years.value[newIndexes[0]];
  
  // 如果选择的是当前年份，需要限制月份选择
  if (selectedYear === currentYear.value) {
    // 重新计算月份列表
    // 如果选择的月份大于当前月份，则设置为当前月份
    if (parseInt(months.value[newIndexes[1]]) > currentMonth.value) {
      newIndexes[1] = months.value.findIndex(m => parseInt(m) === currentMonth.value);
    }
  }
  
  selectedIndexes.value = newIndexes;
};

// 获取当前选中的日期格式化字符串
const getFormattedDate = () => {
  const year = years.value[selectedIndexes.value[0]];
  const month = months.value[selectedIndexes.value[1]];
  return `${year}.${month}`;
};

// 确认选择
const confirm = () => {
  const formattedDate = getFormattedDate();
  emit('confirm', formattedDate);
  close();
};

// 关闭选择器
const close = () => {
  emit('update:visible', false);
  emit('cancel');
};

// 暴露方法给父组件
defineExpose({
  close,
  confirm
});
</script>

<style lang="scss">
.date-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color:rgba(250, 246, 246, 0.5);
  z-index: 1100;
  display: flex;
  align-items: flex-end;
}

.date-picker-container {
  width: 100%;
  background-color: #F4F4F6;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;
  animation: slide-up 0.3s ease;
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.date-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
}

.cancel-btn {
  color: #999;
  font-size: 32rpx;
}

.title {
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
}

.confirm-btn {
  color: #ff4d4f;
  font-size: 32rpx;
  font-weight: 500;
}

.date-picker-content {
  height: 400rpx;
  position: relative;
}

.picker-view {
  width: 100%;
  height: 100%;
}

.picker-item {
  line-height: 80rpx;
  text-align: center;
  font-size: 36rpx;
  color: #333;
}

.date-picker-footer {
  padding: 20rpx 0;
  display: flex;
  justify-content: center;
}

.indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ffffff;
  border-radius: 4rpx;
}
</style>